package org.beanutopia.function;

import com.google.common.base.Predicate;
import static com.google.common.base.Predicates.alwaysTrue;
import static com.google.common.base.Predicates.isNull;

import java.util.Comparator;
import static java.lang.System.identityHashCode;

/**
 * @author ymeymann
 * @since Dec 4, 2007 3:27:45 PM
 */
public class PredicateComparator implements Comparator<Predicate<?>> {

  private static final PredicateComparator instance = new PredicateComparator();

  public static PredicateComparator getInstance() {
    return instance;
  }

  public static final Predicate<Object> ALWAYS_TRUE = alwaysTrue();
  public static final Predicate<Object> IS_NULL = isNull();

  public int compare(Predicate<?> o1, Predicate<?> o2) {
    if (o1.equals(o2)) return 0;
    if (IS_NULL.equals(o1)) return -1;
    if (IS_NULL.equals(o2)) return 1;
    if (ALWAYS_TRUE.equals(o1)) return 1;
    if (ALWAYS_TRUE.equals(o2)) return -1;
    if (o1 instanceof TypePredicate && o2 instanceof TypePredicate) {
      Class<?> c1 = ((TypePredicate)o1).getMatchClass();
      Class<?> c2 = ((TypePredicate)o2).getMatchClass();
      if (c1.equals(c2)) {
        return 0;
      } else {
        return c1.isAssignableFrom(c2) ? 1 : -1;
      }
    }
    return identityHashCode(o1) > identityHashCode(o2) ? 1 : -1;
  }
}
